<script setup lang="jsx">
import TableBase from '@/components/Table-Base.vue'
import DialogBase from '@/components/Dialog-Base.vue'
import SearchForm from '@/components/Search-Form.vue'
import MainContent from '@/components/Main-Content.vue'
import { ref, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { TimeIcon, CheckIcon, HistoryIcon, CloseIcon } from 'tdesign-icons-vue-next'
import {
    addContractItem, cancelContractItem,
    delCompanyItem,
    delContractItem,
    getCompanyList,
    getSecondCompanyList
} from '@/api/company'
import { useRouter } from 'vue-router'
import { getToken } from '@/utils/storage'
import { getBuildingOptions } from '@/api/building'

const router = useRouter()
const contractStatusMap = {
    0: '待生效',
    1: '生效中',
    2: '已到期',
    3: '已退租',
    '待生效': 'primary',
    '生效中': 'success',
    '已到期': 'warning',
    '已退租': 'danger',
    '待生效icon': <TimeIcon />,
    '生效中icon': <CheckIcon />,
    '已到期icon': <HistoryIcon />,
    '已退租icon': <CloseIcon />
}
const requestHeaders = {
    Authorization: 'Bearer ' + getToken()
}
const formData = ref({})
const query = ref({
    page: 1,
    pageSize: 10
})
const currentRowId = ref()
const columns = ref([
    {
        title: '序号',
        colKey: 'serial-number',
        width: 80
    },
    {
        title: '企业名称',
        colKey: 'name'
    },
    {
        title: '负责人员',
        colKey: 'contact'
    },
    {
        title: '联系电话',
        colKey: 'contactNumber'
    },
    {
        title: '操作',
        colKey: 'option'
    }
])
const listData = ref({
    list: [],
    total: 0
})
const secondColumns = ref([
    {
        title: '序号',
        colKey: 'serial-number',
        width: 80
    },
    {
        title: '租赁楼宇',
        colKey: 'buildingName'
    },
    {
        title: '起止时间',
        colKey: 'date'
    },
    {
        title: '合同状态',
        colKey: 'status',
        cell: (h, { row }) => {
            return (
                <t-tag shape="round" theme={ contractStatusMap[row.status] } variant="light-outline">
                    { contractStatusMap[row.status + 'icon'] }
                    { row.status }
                </t-tag>
            )
        }
    },
    {
        title: '操作',
        colKey: 'option'
    }
])
const secondListData = ref([])
const secondListLoading = ref(false)
const openRowList = ref([])
const showDialog = ref(false)
const dialogType = ref('add')
const rules = ref({
    buildingId: [
        {
            required: true, message: '请选择租赁楼宇', trigger: 'change'
        }
    ],
    endTime: [
        {
            required: true, message: '请选择起止日期', trigger: 'change'
        }
    ],
    contractUrl: [
        {
            required: true, message: '请上传合同', trigger: 'change'
        }
    ]
})
const fileList = ref([])
const lockStartDate = ref('')
const disableDate = ref({})
const dialogForm = ref({})
const buildingList = ref([])
const dialogCheckedDate = ref([])
const dialogFormInstance = ref(null)

watch(dialogCheckedDate, (newVal) => {
    if (newVal.length > 0) {
        dialogForm.value = {
            ...dialogForm.value,
            startTime: dialogCheckedDate.value[0],
            endTime: dialogCheckedDate.value[1]
        }
    }
})

const search = async () => {
    const res = await getCompanyList({
        ...query.value,
        ...formData.value
    })
    listData.value.list = res.data.rows
    listData.value.total = res.data.total
}
const reset = () => {
    formData.value = {}
    search()
}
const addCompany = async () => {
    await router.push('/park/company/form?type=add')
}
const closeDialog = () => {
    showDialog.value = false
    if (dialogFormInstance.value) dialogFormInstance.value.clearValidate()
}
const clickClose = () => {
    showDialog.value = false
    dialogCheckedDate.value = []
    fileList.value = []
    disableDate.value = {}
    if (dialogFormInstance.value) dialogFormInstance.value.reset()
}
const uploadSuccess = ({ response: { data } }) => {
    const params = {
        contractId: data.id,
        contractUrl: data.url
    }
    dialogForm.value = { ...dialogForm.value, ...params }
}
const dialogConfirm = async () => {
    const valid = await dialogFormInstance.value.validate()
    if (typeof valid === 'boolean' && valid) {
        if (dialogType.value === 'addContract') {
            const res = await addContractItem({
                ...dialogForm.value,
                type: 0,
            })
            if (res.code !== 10000) return
            clickClose()
            await MessagePlugin.success('添加成功！')
        } else {
            const res = await addContractItem({
                ...dialogForm.value,
                type: 1,
            })
            if (res.code !== 10000) return
            clickClose()
            await MessagePlugin.success('续租成功！')
            await getSecondCompany(currentRowId.value)
        }
    }
}
const openRow = async ({ list }) => {
    secondListLoading.value = true
    const key = list.reverse()[0]
    openRowList.value = key === undefined ? [] : [key]

    if (!openRowList.value[0]) return secondListData.value = []

    await getSecondCompany(key)
}
const getSecondCompany = async id => {
    currentRowId.value = id
    const res = (await getSecondCompanyList(id)).data
    secondListData.value = res.map(e => {
        e.date = e.startTime + ' 至 ' + e.endTime
        e.status = contractStatusMap[e.status]
        return e
    })
    secondListLoading.value = false
}
const getRow = async (data, type) => {
    if (type === 'del') {
        const res = await delCompanyItem(data.row.id)
        if (res.code === 10000) {
            await MessagePlugin.success('删除成功!')
            if (listData.value.list.length === 1 && query.value.page > 1) query.value.page--
            await search()
        } else {
            await MessagePlugin.error(res.msg)
        }
    } else if (type === 'edit') {
        await router.push('/park/company/form?type=' + type + '&id=' + data.row.id)
    } else if (type === 'view') {
        await router.push('/park/company/detail?id=' + data.row.id)
    } else if (type === 'addContract') {
        dialogType.value = 'addContract'
        showDialog.value = true
        dialogForm.value.enterpriseId = data.row.id
        buildingList.value = (await getBuildingOptions()).data
    } else if (type === 'continue') {
        dialogType.value = 'continue'
        showDialog.value = true
        dialogForm.value.enterpriseId = currentRowId.value
        dialogForm.value.buildingId = data.buildingName
        const date = new Date(data.endTime)
        date.setDate(date.getDate() + 1)
        const endDate = date.toLocaleString().split(' ')[0].replaceAll('/', '-')
        lockStartDate.value = endDate
        dialogCheckedDate.value = [endDate]
        disableDate.value = { before: endDate }

        buildingList.value = (await getBuildingOptions()).data
        buildingList.value = [
            {
                id: data.buildingId,
                name: data.buildingName
            },
            ...buildingList.value]
        dialogForm.value.buildingId = data.buildingId
        dialogFormInstance.value.clearValidate()
    } else if (type === 'cancel') {
        const res = await cancelContractItem(data.id)
        if (res.code === 10000) {
            await MessagePlugin.success('删除成功!')
            await getSecondCompany(currentRowId.value)
        } else {
            await MessagePlugin.error(res.msg)
        }
    } else if (type === 'delContract') {
        const res = await delContractItem(data.id)
        if (res.code === 10000) {
            await MessagePlugin.success('删除成功!')
            await getSecondCompany(currentRowId.value)
        } else {
            await MessagePlugin.error(res.msg)
        }
    }
}
const datePickerChange = e => {
    if (dialogType.value === 'addContract') return
    dialogCheckedDate.value = [lockStartDate.value, e[1]]
    dialogForm.value.startTime = e[0]
    dialogForm.value.endTime = e[1]
}

search()
</script>

<template>
    <main-content>
        <search-form>
            <t-form
                ref="form"
                :data="formData"
                label-width="auto"
                layout="inline"
            >
                <t-form-item label="企业名称">
                    <t-input v-model.trim="formData.name" placeholder="请输入企业名称"></t-input>
                </t-form-item>
                <t-form-item style="min-width: auto">
                    <t-button @click="search" type="submit" style="margin-right: 10px;">查询</t-button>
                    <t-button @click="reset" variant="outline">重置</t-button>
                </t-form-item>
            </t-form>
        </search-form>

        <table-base :columns="columns" :list="listData.list" :showExpandIcon="true"
                    :openRowList="openRowList" @openRow="openRow">
            <template #top-btn>
                <t-button theme="primary" @click="addCompany">添加企业</t-button>
            </template>
            <template #option-table="row">
                <t-button variant="text" theme="primary" @click="getRow(row, 'addContract')">添加合同</t-button>
                <t-button variant="text" theme="primary" @click="getRow(row, 'view')">查看</t-button>
                <t-button variant="text" theme="primary" @click="getRow(row, 'edit')">编辑</t-button>
                <t-popconfirm
                    destroyOnClose
                    showArrow
                    @confirm="getRow(row, 'del')"
                    theme="warning" content="确认删除吗">
                    <t-button variant="text" theme="primary" :disabled="!!row.row.existContractFlag">删除</t-button>
                </t-popconfirm>
            </template>
            <template #expanded-content="{ row }">
                <t-card class="table-card">
                    <t-table
                        class="secondTable"
                        hover
                        rowKey="id"
                        :loading="secondListLoading"
                        :data="secondListData"
                        :columns="secondColumns"
                    >
                        <template #option="{ row }">
                            <t-button variant="text" theme="primary"
                                      @click="getRow(row, 'continue')"
                                      :disabled="!row.renewFlag">续租</t-button>
                            <t-popconfirm
                                destroyOnClose
                                showArrow
                                @confirm="getRow(row, 'cancel')"
                                theme="warning" content="确认退租吗">
                                <t-button variant="text" theme="primary" :disabled="!row.exitFlag">退租</t-button>
                            </t-popconfirm>
                            <t-popconfirm
                                destroyOnClose
                                showArrow
                                @confirm="getRow(row, 'delContract')"
                                theme="warning" content="确认删除吗">
                                <t-button variant="text" theme="primary" :disabled="row.status !== '已退租'">删除</t-button>
                            </t-popconfirm>
                        </template>
                    </t-table>
                </t-card>
            </template>
        </table-base>

        <dialog-base :showDialog="showDialog"
                     :dialogType="dialogType"
                     :dialogTitle="dialogType === 'add' ? '添加员工' : '编辑员工'"
                     @dialogConfirm="dialogConfirm"
                     @clickClose="clickClose"
                     @closeDialog="closeDialog">
            <t-form class="dialogForm" ref="dialogFormInstance" labelAlign="top"
                    :rules="rules" :data="dialogForm">
                <t-form-item label="租赁楼宇" name="buildingId">
                    <t-select
                        filterable
                        :disabled="dialogType === 'continue'"
                        placeholder="请选择租赁楼宇"
                        v-model.trim="dialogForm.buildingId"
                        showArrow>
                        <t-option v-for="e in buildingList" :value="e.id" :key="e.id" :label="e.name"/>
                    </t-select>
                </t-form-item>
                <t-form-item label="起止日期" name="endTime">
                    <t-date-range-picker allow-input clearable
                                         v-model:disableDate="disableDate"
                                         :placeholder="['开始日期', '结束日期']"
                                         @change="datePickerChange"
                                         v-model.trim="dialogCheckedDate"/>
                </t-form-item>
                <t-form-item label="租赁合同" name="contractUrl">
                    <t-upload action="https://api-hmzs.itheima.net/api/upload"
                              :triggerButtonProps="{ theme: 'primary', variant: 'outline' }"
                              accept=".doc, .docx, .pdf" :headers="requestHeaders"
                              @success="uploadSuccess" :data="{ type: 'contract' }"
                              v-model:files="fileList"
                              placeholder="支持扩展名：.doc .docx .pdf, 文件大小不得超过5M"/>
                </t-form-item>
            </t-form>
        </dialog-base>
    </main-content>
</template>

<style scoped lang="scss">
:deep .table-card {
    .t-card__body {
        padding: 0;

        .t-table {
            border-radius: var(--td-radius-medium);

            .t-table__content {
                border-radius: var(--td-radius-medium);

                .t-table__body {
                    tr:last-of-type {
                        td {
                            border-bottom: 0;
                        }
                    }
                }
            }
        }

        .t-loading__overlay {
            border-radius: var(--td-radius-medium);
        }
    }
}

.t-date-range-picker {
    width: 100%;
}
</style>
